<template>
  <div class="outcomesUploadFilePage">
    <!-- <h2>{{fileName}}</h2> -->
    <div class="btnBox">
      <!-- <button>创建</button> -->
      <el-button type="primary" size="mini" @click="openWriteName">新建目录</el-button>
      <span style="display: inline-block; margin-left: 10px;">
        <upload style="display: inline-block;" :buttonType="'primary'" :isStuShow="true" :buttonSize="'mini'" :showFileList="false" :currNo="Number($route.query.currNo || currNo)" :baseFileUrl="baseFileUrl" :uploadedFileList="fileList" @uploadedBefore="uploadedBefore" @fileDataUploaded="fileDataUploadedToRootPath">
          <template #default>
            <el-button type="primary" size="mini">上传</el-button>
          </template>
        </upload>
        <span style="margin-left: 10px">文件大小:建议大小不超过60M,系统会定时清理超过60M的文件;文件最大不超过80M</span>
      </span>
      <!-- <button>上传压缩包</button> -->
      <!-- <button>编辑</button> -->
      <!-- <button>复制学业链接</button> -->
    </div>
    <div class="fileTree">
      <div class="fileTree-head">
        <div class="name">
          <!-- <el-checkbox v-model="checkedAll" /> -->
          名称
        </div>
        <div class="size">大小</div>
        <div class="updateTime">修改时间</div>
      </div>
    </div>
    <div class="treeFile">
      <TreeFile
        :fileList="fileList"
        :showCheckBox="false"
        :nodeKey="'id'"
        :expandAll="false"
        :expandOnClickNode="false"
        :defaultProps="defaultProps"
        :className="'filePageTree'"
        ref="tree"
        :showMoreBtn="true"
        @append="openWriteName"
        @remove="remove"
        @handleClickNode="handleClickNode"
        @fileDataUploaded="fileDataUploaded"
        @copy="handlecopy"
        @handleSetHomePage="handleSetHomePage"
        @decompression="handleDecompressionToFolder"
        @downLoad="handleDownLoad"
        @newDownLoad="handleNewDownLoad"
        :baseFileUrl="baseFileUrl"
        :text="'新建子目录'"
        :isStuShow="true"
        :unShowDeleteBtn="true"
        :currNo="Number($route.query.currNo || currNo)" 
      />
      <span>文件大小:建议大小不超过60M,系统会定时清理超过60M的文件;文件最大不超过80M</span>
    </div>
    <!-- 文件预览组件 -->
    <previewImgVidoeFile
      :showPerview="amplify"
      @close="handelclose"
      :showData="amplifyFile"
      :fileList="fileList"
    />
    <writeFileName
      v-if="writeFileNameShow"
      :writeFileNameShow.sync="writeFileNameShow"
      :writeFileNameText='writeFileNameText'
      @handleConfirm="append($event, currNode, currData)"
      @handleCancel="handleCancel"
    />
    <DPFileToFolder :showDialog="showFileToFolder" :fileList="fileList" :tree="$refs['tree']" :showFileToFolderNode="showFileToFolderNode" :showFileToFolderData="showFileToFolderData" 
      @close="handleCloseFileToFolder" @append="openWriteName" @remove="remove" @confirm="confirmDecompression" @newFile="openWriteName"
    />
  </div>
</template>

<script>
import { addFolder, deleteFile } from "@/request/folder";
import { mapState } from "vuex";
const TreeFile = () => import("@/components/treeFile/index");
import { Decompression, recursionFilePath } from "@/util/decompression.js";
import { location, handelItem, copy } from "@/util/tool";
const previewImgVidoeFile = () =>
  import("@/components/previewImgVidoeFile/previewImgVidoeFile");
const writeFileName = () =>
  import("@/views/user/user/component/writeFileName.vue");
let id = 1000;
import { stuShowUpdate, getStuShowDetail, getStuShowDetailToUser } from "@/request/stushow.js";
const DPFileToFolder = () => import("@/components/dPressionFileToFolder/index");
const upload = () => import("@/components/upload/index.vue")
import { Upload } from "@/util/upload.js"
import { Video } from "@/util/videoUrlFormat";
import { directDownload, rangeDownload } from "@/util/download.js"
export default {
  components: {
    TreeFile,
    previewImgVidoeFile,
    writeFileName,
    upload,
    DPFileToFolder
  },
  data() {
    return {
      checkedAll: false,
      defaultProps: {
        children: "subFiles",
        label: "fileName",
      },
      fileList: [],
      folderFomart: {
        fileName: "新的文件夹",
        fileUrl: "",
        subFiles: [],
        isDir: true,
      },
      amplifyFile: {},
      amplify: false,
      isEncoded: false,
      writeFileNameShow: false,
      writeFileNameText: "",
      currNode: {},
      currData: {},
      fileName: "课程名",
      showFileToFolder: false,
      showFileToFolderNode: {},
      showFileToFolderData: {},
    };
  },
  props: {
    isEdit: Boolean,
    currSelctStuShow: Object,
    stuworkshowID: Number,
    currNo: Number,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      stuShowList: (state) => state.stuShow.stuShowList
    }),
    handleCheckType() {
      return (type, arrType) => {
        return arrType.indexOf(type) !== -1;
      };
    },
    baseFileUrl() {
      const { query } = this.$route;
      return `/stutasks/userID_${this.userInfo.userID}/currNo_${query.currNo || this.currNo}`;
    }
  },
  watch: {
    "$store.state.stuShow.stuShowList"(n) {
      this.initStuShowDataList()
    },
    "$store.state.courses.chooseCourses"(n) {
        this.initCourseName(n)
    }
  },
  created() {
    this.initStuShowDataList()
    this.initCourseName(this.$store.state.courses.chooseCourses)
  },
  methods: {
    // 初始化课程名
    initCourseName(n) {
      if (n.length) {
        const fCourse = n.find(item => item.currNo == Number(this.$route.query.currNo || this.currNo))
        fCourse && (this.fileName = fCourse.name)
      }
    },
    openWriteName(node, data, text) {
      this.writeFileNameShow = true;
      this.writeFileNameText = text ? text: '新建目录' 
      this.currNode = node;
      this.currData = data;
    },
    handleCancel() {
      this.writeFileNameShow = false;
      this.currNode = {};
      this.currData = {};
    },
    // 添加
    async append(fileName, node, data) {
      this.writeFileNameShow = false;
      const newChild = {
        // id: id++,
        fileName: fileName,
        fileUrl: "",
        subFiles: [],
        isDir: true,
      };
      if (node?.level >= 1) {
        const check = this.checkFileNameIsRepeat(fileName, node, data);
        if (!check) return
        const parentPath = node.data.fileUrl
        const baseFileUrl = this.baseFileUrl + parentPath;
        newChild.fileUrl = parentPath + `/${newChild.fileName}`;
        const res = await this.aFolder(newChild, baseFileUrl);
        if (res.errno === 0) {
          if (!data.subFiles) {
            this.$set(data, "subFiles", []);
          }
          newChild.id = id++;
          data.subFiles.push(newChild);
          // 保存数据
          this.handleUpdateStuShowData()
        } else {
          this.$antdMessage.error({
            content: res.message || res
          })
        }
      } else {
        const check = this.checkFileNameIsRepeat(fileName, node, data);
        if (!check) return
        newChild.id = id++;
        newChild.subFiles = [];
        newChild.fileUrl = "/" + newChild.fileName;
        const res = await this.aFolder(newChild, this.baseFileUrl);
        if (res.errno === 0) {
          this.fileList.push(newChild);
          // 保存数据
          this.handleUpdateStuShowData()
        } else {
          this.$antdMessage.error({
            content: res.message || res
          })
        }
      }
    },
    // 删除
    async remove(node, data) {
      const { fileName } = data;
      let baseFileUrl = this.baseFileUrl.substring(1);
      if (node.level !== 1) {
        baseFileUrl = baseFileUrl + node.parent.data.fileUrl;
      }
      const params = {
        fileOrFolderName: fileName,
        currNo: Number(this.$route.query.currNo || this.currNo),
        isStuShow: true,
        baseFileUrl: baseFileUrl,
        subPath: baseFileUrl
      };
      const res = await deleteFile(params);
      if (res.errno === 0) {
        const parent = node.parent;
        const subFiles = parent.data.subFiles || parent.data;
        const index = subFiles.findIndex((d) => d.id === data.id);
        subFiles.splice(index, 1);
        this.handleUpdateStuShowData()
        this.$antdMessage.success({content: '删除成功!'})
      } else {
        this.$antdMessage.error({
          content: res.message || "删除失败!",
        });
      }
    },
    // 新建文件夹
    async aFolder(fileData, baseFileUrl) {
      const currNo = Number(this.$route.query.currNo || this.currNo);
      const userID = this.userInfo.userID;
      baseFileUrl = baseFileUrl.substring(1);
      if (!currNo)
        return this.$antdMessage.error({
          content: "创建失败,无法获取当前学业的课程ID!",
        });
      if (!userID)
        return this.$antdMessage.error({ content: "获取用户信息失败!" });
      // return {
      //   errno: 0,
      // };
      const res = await addFolder({
        isStuShow: true,
        foldername: fileData.fileName,
        currNo: currNo,
        baseFileUrl: baseFileUrl,
        subPath: baseFileUrl,
      });
      return res;
    },
    // 检查当前目录下是否有相同文件名的文件夹
    checkFileNameIsRepeat(fileName, node, data) {
      if (node?.data) {
        const findFileName = node.data.subFiles.find(item => item.fileName === fileName)
        if (findFileName) {
          this.$antdMessage.warning({content: `已存在${fileName}文件!`}) 
          return false
        } else return true
      } else {
        const findFileName = this.fileList.find(item => item.fileName === fileName)
        if (findFileName) {
          this.$antdMessage.warning({content: `已存在${fileName}文件!`}) 
          return false  
        }
        else return true
      }

    },
    // 递归获取所有父级拼接的文件名
    getBaseFileUrl(node, currFileUrl) {
      let url = currFileUrl;
      // if (Array.isArray(node.parent.data)) return url
      if (node.level >= 1) {
        return this.getBaseFileUrl(node.parent, url);
      } else return url;
    },
    // 解压文件
    async handleDecompression(node, item, unzipFilePath) {
      const fileUrl = item.fileUrl.split(location(window))[1];
      const res = await Decompression(fileUrl, unzipFilePath);
      if (!res) return;
      // 递归文件路径
      let subFiles = this.fileNameSetToFileUrl(res.data.filePaths) || [];
      subFiles = Upload.addHttpLocation(subFiles, node.data.fileUrl)
      // 将递归后的文件格式,设置给对应saveUseFileList索引文件的subFiles属性
      this.$set(node.data, "subFiles", subFiles);
      // 第一个解压的文件无法自动展开
      this.$nextTick(() => {
        node.expanded = true;
      });
      // 保存数据
      this.handleUpdateStuShowData()
    },
    // 将文件名转为路径
    fileNameSetToFileUrl(arr) {
      let subArr = []
      arr.forEach(item => {
        if (!item.fileUrl) item.fileUrl = "/" + item.fileName
        if (item.subFiles?.length) {
          this.fileNameSetToFileUrl(item.subFiles)
        }
        subArr.push(item)
      })
      return subArr
    },
    // 点击节点
    handleClickNode(e, node, data) {
      data = Object.assign({}, data)
      if (data.isDir) return  this.$nextTick(() => { node.expanded = !node.expanded });
      data.fileUrl =  this.getCompleteFileUrl(data.fileUrl)
      // 执行对不同的类型的节点处理
      handelItem(node, data, this)
    },
    // 关闭预览引导文文件窗口
    handelclose() {
      this.amplify = false;
    },
    // 上传文件到根目录
    fileDataUploadedToRootPath(baseFileUrl, data) {
      this.fileList.push(data)
      this.handleUpdateStuShowData()
    },
    // 将上传的文件插入到列表
    fileDataUploaded(node, data, fileData) {
      // 拼接所有父级的URL
      fileData.fileUrl = this.getBaseFileUrl(node,data.fileUrl) + fileData.fileUrl
      data.subFiles.push(fileData)
      this.handleUpdateStuShowData()
    },
    // 修改学业数据
    async handleUpdateStuShowData(homepagepath) {
      const { query } = this.$route
      let currSelectStuShow = this.currSelctStuShow
      if(!this.currSelctStuShow) {
        let { stuworkshowID } = query
        if (!stuworkshowID) stuworkshowID = this.stuworkshowID
        const findStuShow = this.stuShowList.find(item => item.stuworkshowID == stuworkshowID)
        if (findStuShow) this.currSelctStuShow = findStuShow
      }
      let params = Object.assign({}, currSelectStuShow)
      if (!params.stuworkshowID || !params.currNo) {
        const gStuShowData = await getStuShowDetailToUser({currNo: query.currNo || this.currNo, userID: this.userInfo.userID})
        if (!gStuShowData) return this.$antdMessage.warning({content: '缺少学业数据!'}) 
        params = gStuShowData
        if (!params.stuworkshowID || !params.currNo) {
          return this.$antdMessage.warning({
            content: `缺少${!params.stuworkshowID? 'stuworkshowID':'currNo'}参数`
          })
        }
      }
      if (homepagepath) params.homepagepath = homepagepath
      params.filepaths = JSON.parse(JSON.stringify(this.fileList)) || []
      Upload.deleteHttpLocation(params.filepaths)
      const res = await stuShowUpdate(params)
      if (res.errno == 0) {
        this.$antdMessage.success({content: '修改成功!'})
        this.$store.commit("stuShow/stushowDataUpadateToList", params)
      } else this.$antdMessage.error({content: res.message || '修改失败!'})
    },
    // 初始化文件列表
    async initStuShowDataList() {
      let stuworkshowID = this.$route.query.stuworkshowID || this.stuworkshowID
      let findStuShow = this.$store.state.stuShow.stuShowList.find(item => item.stuworkshowID == stuworkshowID)
      if (!findStuShow) {
        await this.$store.dispatch('stuShow/gStuShowList', {userID : this.userInfo.userID})
        findStuShow = this.$store.state.stuShow.stuShowList.find(item => item.stuworkshowID == stuworkshowID)
      }
      // const findStuShow = this.$store.state.stuShow.stuShowList.find(item => item.stuworkshowID == this.$route.query.stuworkshowID)
      // findStuShow.filepaths = [{"isDir":true,"fileUrl":"/test11","fileName":"test11","subFiles":[{"isDir":true,"fileUrl":"/test","fileName":"test","subFiles":[{"isDir":true,"fileUrl":"/c1","fileName":"c1","subFiles":[{"isDir":false,"fileUrl":"/c1.txt","fileName":"c1.txt"},{"isDir":true,"fileUrl":"/c2","fileName":"c2","subFiles":[{"isDir":false,"fileUrl":"/c2.txt","fileName":"c2.txt"}]}]}]}]},{"type":"zip","isDir":false,"fileUrl":"/test.zip","fileName":"test.zip"},{"type":"png","isDir":false,"fileUrl":"/粤康码小程序.png","fileName":"粤康码小程序.png"}]
      if (findStuShow) {
        Upload.deleteHttpLocation(findStuShow.filepaths)
        this.fileList = Upload.addHttpLocation(findStuShow.filepaths)
      }
    },
    // 复制
    handlecopy(node, data) {
      copy(this.getCompleteFileUrl(node.data.fileUrl))
    },
    handleSetHomePage(node, data) {
      this.handleUpdateStuShowData(data.fileUrl)
    },
    uploadedBefore(data) {
      if (!data.fileObj) return
      this.fileDataUploadedToRootPath(Video.urlFormat(data.fileObj, false));
    },
    // 解压到指定文件夹
    handleDecompressionToFolder(node, data) {
      // const 
      this.showFileToFolder = true
      this.showFileToFolderNode = node
      this.showFileToFolderData = data
    },
    // 下载文件
    handleDownLoad(node, data) {
      const url = this.getCompleteFileUrl(data.fileUrl)
      window.open(url)
    },
    // 移除url头部
    removeHttpUrl(url) {
      return url.replace('http://test.codelover.club', '').replace('https://test.codelover.club', '').replace('https://codelover.club', '').replace('https://www.codelover.club', '').replace('http://10.1.6.130', '')
    },
    handleNewDownLoad(node, data) {
      // directDownload(this.removeHttpUrl(data.fileUrl) ,data, this.userInfo.accessToken)
      rangeDownload('/files' + this.baseFileUrl + this.removeHttpUrl(data.fileUrl) ,data, this.userInfo.accessToken)
    },
    // 获取完整的文件路径 对host、base路径拼接
    getCompleteFileUrl(fileUrl) {
      if(fileUrl.indexOf('http://') !== -1 || fileUrl.indexOf('https://') !== -1)
        return fileUrl
      return location(window) + '/files' + this.baseFileUrl + fileUrl
    },
    // 关闭选择解压路径弹出框
    handleCloseFileToFolder() {
      this.showFileToFolder = false
      this.showFileToFolderNode = {}
      this.showFileToFolderData = {}
    },
    // 确认解压
    confirmDecompression(node, data, selectFolderNode, selectFolderData) {
      const file = {
        fileUrl: location(window) + this.baseFileUrl + data.fileUrl
      }
      this.handleDecompression(selectFolderNode, file , this.baseFileUrl + selectFolderData.fileUrl)
    }
  }, 
};
</script>

<style lang="stylus" scoped>
.outcomesUploadFilePage {
  flex: 1;

  .btnBox {
    margin-bottom: 10px;
  }

  .fileTree {
    .fileTree-head {
      padding-left: 20px;
      display: flex;
      align-items: center;
      height: 48px;
      background-color: #e7e8f1;
      font-family: Source Han Sans CN;
      font-size: 1rem;
      color: #1b1b1c;

      .name {
        width: 252px;
        overflow: hidden;
        line-height: 48px;

        .addFilePage {
          cursor: pointer;
        }
      }

      .size {
        width: 108px;
        line-height: 48px;
      }

      .updateTime {
        min-width: 150px;
        line-height: 48px;
      }
    }
  }
}
</style>